package com.global.emc.spring.exception.handler.convert;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;

import com.global.emc.core.exception.IEMCException;
import com.global.emc.core.exception.handler.IConvertEMCExceptionHandler;
import com.global.emc.core.exception.impl.FormValidationEMCException;

/**   
 *  
 * @Description:  [将BindException类型异常转化为FormValidationEMCException类型异常]   
 * @Author:       [Joly_Huang]   
 * @CreateDate:   [2014年2月20日 下午10:38:25]   
 * @UpdateUser:   [Joly_Huang]   
 * @UpdateDate:   [2014年2月20日 下午10:38:25]   
 * @UpdateRemark: [说明本次修改内容]  
 * @Version:      [v1.0] 
 *    
 */
public class ConvertBindExceptionToFormValidationEMCExceptionHandler implements IConvertEMCExceptionHandler {

	@Override
	public boolean supports(Exception exception) {
		return exception instanceof BindException;
	}
	
	@Override
	public IEMCException convertMessagesToEMCException(Exception exception) {
		return convertBindExceptionToFormValidationEMCException((BindException) exception);
	}

	protected FormValidationEMCException convertBindExceptionToFormValidationEMCException(BindException bindException) {
		FormValidationEMCException formValidationEMCException = new FormValidationEMCException(bindException);
		Map<String, List<String>> fieldErrors = new HashMap<String, List<String>>();

		for (FieldError fieldError : bindException.getFieldErrors()) {
			String code = fieldError.getCode();
			String[] codes = fieldError.getCodes();
			fieldErrors.put(codes[1].substring(code.length() + 1), null);
		}

		formValidationEMCException.setFieldErrors(fieldErrors);
		
		return formValidationEMCException;
	}

	
}
